<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="预案名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入预案名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="窗口模式" prop="wndMode">
              <el-select v-model="queryParams.wndMode" clearable>
                <el-option v-for="(item, index) in wndModes" :key="index" :value="item.value">{{ item.label }}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['biz:videoPlan:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table
        ref="videoPlanTableRef"
        v-loading="loading"
        :data="videoPlanList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column label="预案名称" prop="name" />
        <el-table-column label="是否预案" align="center" prop="isPlan">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isPlan" />
          </template>
        </el-table-column>
        <el-table-column label="窗口模式" align="center" prop="wndMode" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['biz:videoPlan:edit']" />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['biz:videoPlan:add']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['biz:videoPlan:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改视频预案对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body @opened="initPlayer" @closed="stopPlayer">
      <el-form ref="videoPlanFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="预案名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入预案名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="videoPlanOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="请选择上级"
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="编辑预案" prop="isPlan">
              <el-switch v-model="form.isPlan" @change="editChange" active-value="Y" inactive-value="N" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.isPlan === 'Y'">
            <el-form-item label="窗口模式" prop="wndMode">
              <el-select v-model="form.wndMode" clearable>
                <el-option v-for="(item, index) in wndModes" :key="index" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="form.isPlan === 'Y'">
          <el-col :span="6">
            <el-tree :data="cameraTree" class="cameraTree"></el-tree>
          </el-col>
          <el-col :span="18">
            <h5-player ref="playerRef" :split-num="form.wndMode" style="width: 100%; height: 400px" />
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="VideoPlan" lang="ts">
import { listVideoPlan, getVideoPlan, delVideoPlan, addVideoPlan, updateVideoPlan } from '@/api/biz/videoPlan';
import { VideoPlanVO, VideoPlanQuery, VideoPlanForm } from '@/api/biz/videoPlan/types';
import H5Player from '@/views/biz/components/h5player';

type VideoPlanOption = {
  id: number;
  name: string;
  children?: VideoPlanOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));

const videoPlanList = ref<VideoPlanVO[]>([]);
const videoPlanOptions = ref<VideoPlanOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);
const playerRef = ref(null);

const queryFormRef = ref<ElFormInstance>();
const videoPlanFormRef = ref<ElFormInstance>();
const videoPlanTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const editChange = (e) => {
  if (e === 'N') {
    form.value.wndMode = null;
    form.value.cameras = null;
  } else {
  }
};

const initPlayer = () => {
  setTimeout(() => {
    playerRef.value.createPlayer();
  }, 1000);
};

const stopPlayer = () => {
  playerRef.value.stopAllPlay();
};

const wndModes = [
  {
    'value': 1,
    'label': '1*1'
  },
  {
    'value': 2,
    'label': '2*2'
  },
  {
    'value': 3,
    'label': '3*3'
  },
  {
    'value': 4,
    'label': '4*4'
  }
];

const cameraTree = [
  {
    'label': '区域1',
    'id': 1,
    'children': [
      {
        'label': '摄像机1',
        'id': 1,
        'children': []
      },
      {
        'label': '摄像机2',
        'id': 1,
        'children': []
      }
    ]
  },
  {
    'label': '区域2',
    'id': 1,
    'children': [
      {
        'label': '摄像机3',
        'id': 1,
        'children': []
      },
      {
        'label': '摄像机4',
        'id': 1,
        'children': []
      }
    ]
  }
];

const initFormData: VideoPlanForm = {
  id: undefined,
  name: undefined,
  wndMode: undefined,
  parentId: undefined,
  cameras: undefined,
  isPlan: 'N'
};

const data = reactive<PageData<VideoPlanForm, VideoPlanQuery>>({
  form: { ...initFormData },
  queryParams: {
    name: undefined,
    wndMode: undefined,
    parentId: undefined,
    cameras: undefined,
    isPlan: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '预案名称不能为空', trigger: 'blur' }],
    parentId: [{ required: true, message: '父编号不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询视频预案列表 */
const getList = async () => {
  loading.value = true;
  const res = await listVideoPlan(queryParams.value);
  const data = proxy?.handleTree<VideoPlanVO>(res.data, 'id', 'parentId');
  if (data) {
    videoPlanList.value = data;
    loading.value = false;
  }
};

/** 查询视频预案下拉树结构 */
const getTreeselect = async () => {
  const res = await listVideoPlan();
  videoPlanOptions.value = [];
  const data: VideoPlanOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<VideoPlanOption>(res.data, 'id', 'parentId');
  videoPlanOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  videoPlanFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: VideoPlanVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加视频预案';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(videoPlanList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: VideoPlanVO[], status: boolean) => {
  data.forEach((item) => {
    videoPlanTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: VideoPlanVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getVideoPlan(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改视频预案';
};

/** 提交按钮 */
const submitForm = () => {
  videoPlanFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateVideoPlan(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addVideoPlan(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: VideoPlanVO) => {
  await proxy?.$modal.confirm('是否确认删除视频预案编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delVideoPlan(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  width: 120px;
}

.cameraTree {
  height: 500px;
}
</style>
